package com.sunshine.lnuplus.utils

import android.content.Context
import android.net.Uri
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.sunshine.lnuplus.callback.LoginCallBack
import com.sunshine.lnuplus.model.InitData
import com.sunshine.lnuplus.model.LessonBean
import com.sunshine.lnuplus.model.room.TimetableRepository
import es.dmoral.toasty.Toasty
import java.lang.Exception
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList

/**
 * Created by sunshine on 2020/3/29
 */

object BandRUtils {

    fun b(uri: Uri?, context: Context) : Boolean{
        return if(uri == null) {
            false
        } else {
            val outputStream = context.contentResolver.openOutputStream(uri)
            val gson = Gson()
            val strBuilder = StringBuilder()
            InitData.lessonList?.forEach {
                strBuilder.append(gson.toJson(it)).append(",")
            }

            try {
                outputStream?.write(strBuilder.toString().substring(0, strBuilder.toString().length - 1).toByteArray())
                true
            }catch (e: Exception){
                false
            }
        }
    }

    fun bIcs(uri: Uri?, context: Context) : Boolean{
        return if(uri == null) {
            false
        } else {
            val outputStream = context.contentResolver.openOutputStream(uri)
            val thisWeek = DateUtils.getThisWeek(InitData.lessonStyle.startMonth, InitData.lessonStyle.startDay)
            val dateFormat = SimpleDateFormat("MM/dd")
            val strBuilder = StringBuilder()
            strBuilder
                .append("BEGIN:VCALENDAR\n")
                .append("PRODID:-//Microsoft Corporation//Outlook 11.0 MIMEDIR//EN\n")
                .append("VERSION:2.0\n")
            for (week in thisWeek..InitData.lessonStyle.weekCount){
                InitData.lessonList?.forEach {
                    if(it.weeks.contains(week)){
                        val beginDate = Date()
                        val calendar = Calendar.getInstance()
                        calendar.time = beginDate
                        calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) + (it.dayOfWeek - DateUtils.getTodayOfWeek() + 7 * (week - thisWeek)))
                        val endDate = dateFormat.parse(dateFormat.format(calendar.time))
                        var startHour = "00"
                        var startMin = "00"
                        var endHour = "00"
                        var endMin = "01"
                        try {
                            val start = InitData.lessonStyle.lessonTime[it.start - 1].split("\n")[0].split(":")
                            val end = InitData.lessonStyle.lessonTime[it.end - 1].split("\n")[1].split(":")
                            startHour = start[0]
                            startMin = start[1]
                            endHour = end[0]
                            endMin = end[1]
                            if(startHour.toInt() < 10) startHour = "0" + start[0].toInt()
                            if(startMin.toInt() < 10) startMin = "0" + start[1].toInt()
                            if(endHour.toInt() < 10) endHour = "0" + end[0].toInt()
                            if(endMin.toInt() < 10) endMin = "0" + end[1].toInt()

                            strBuilder
                                .append("BEGIN:VEVENT\n")
                                .append("DTSTART:").append(DateUtils.year).append(dateFormat.format(endDate).split("/")[0]).append(dateFormat.format(endDate).split("/")[1]).append("T").append(startHour).append(startMin).append("00\n")
                                .append("DTEND:").append(DateUtils.year).append(dateFormat.format(endDate).split("/")[0]).append(dateFormat.format(endDate).split("/")[1]).append("T").append(endHour).append(endMin).append("00\n")
                                .append("LOCATION:").append("${it.teacher} ${it.location}\n")
                                .append("DESCRIPTION:").append("第${it.start}节-第${it.end}节\n")
                                .append("SUMMARY:").append("${it.lessonName}\n")
                                .append("END:VEVENT\n")
                        }catch (e: Exception){}
                    }
                }
            }
            strBuilder
                .append("END:VCALENDAR\n")

            try {
                outputStream?.write(strBuilder.toString().toByteArray())
                true
            }catch (e: Exception){
                false
            }
        }
    }

    fun r(uri: Uri?, context: Context) : Int{
        if(uri == null){
            return 0
        }else if(!uri.path!!.contains("json")){
            return 1
        }else{
            return try {
                val inputStream = context.contentResolver.openInputStream(uri)
                val json = inputStream!!.bufferedReader().readLines()
                val gson = Gson()
                val timetableList= gson.fromJson<List<LessonBean>>(json.toString(), object : TypeToken<List<LessonBean>>() {}.type)
                InitData.lessonList = timetableList as ArrayList<LessonBean>
                LoadLessonUtils.initBackLesson(TimetableRepository(context))
                2
            }catch (e: Exception){
                3
            }

        }
    }
}